/*
 * @lc app=leetcode.cn id=752 lang=java
 *
 * [752] 打开转盘锁
 */

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set; 
// @lc code=start
class Solution {
    public int openLock(String[] deadends, String target) {
        // BFS
        // 存储死亡数组
        Set<String> dead = new HashSet<>();
        for(String str : deadends) {
            dead.add(str);
        }
        // 已经走过的路径
        Set<String> visited = new HashSet<>();

        Queue<String> queue = new LinkedList<>();

        int step = 0;
        queue.offer("0000");
        visited.add("0000");
        
        while(!queue.isEmpty()) {
            int size = queue.size();

            for(int i = 0; i < size; i++) {
                String cur = queue.poll();

                // 判断是否到达终点---遇到死亡数组
                if(dead.contains(cur)) {
                    continue;
                }
                if(cur.equals(target)) {
                    return step;
                }

                // 将相邻未访问的节点加入queue
                for(int j = 0; j < 4; j++) {
                    String up = plusOne(cur, j);
                    if(!visited.contains(up)) {
                        queue.offer(up);
                        visited.add(up);
                    }

                    String down = minusOne(cur, j);
                    if(!visited.contains(down)) {
                        queue.offer(down);
                        visited.add(down);
                    }
                } 
            }
            step++;
        }
        return -1;
    }

    // 将 s[j] 向上拨动一次
    private String plusOne(String s, int j) {
        char[] ch = s.toCharArray();
        if (ch[j] == '9')
            ch[j] = '0';
        else
            ch[j] += 1;
        return new String(ch);
    }

    // 将 s[i] 向下拨动一次
    private String minusOne(String s, int j) {
        char[] ch = s.toCharArray();
        if (ch[j] == '0')
            ch[j] = '9';
        else
            ch[j] -= 1;
        return new String(ch);
    }
    
}
// @lc code=end

